import glob
import sys
import threading
import matplotlib
import pandas as pd

from PyQt5 import QtWidgets
from PyQt5.QtCore import QThread, pyqtSignal, Qt
from PyQt5.QtWidgets import QFileDialog
from stressPrinter.AnkePro import AnkeDataPlot
from stressPrinter.Model.AnkeDataAna import AnkeAna
from stressPrinter.AnkePro.UI.UI_Contrast import Ui_UI_DataContrast
from stressPrinter.AnkePro.UI.UI_DataSyncTip import Ui_DataSyncTip
from stressPrinter.Model import model_setLabelByView, LabelsInit
from stressPrinter.Model.TDDataAna import TDAna

from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib import pyplot as plt
from matplotlib.dates import DateFormatter, AutoDateLocator

matplotlib.use("Qt5Agg")
plt.rcParams["font.sans-serif"] = ["Microsoft YaHei"]  # 设置默认字体
plt.rcParams["axes.unicode_minus"] = False  # 坐标轴正确显示正负号


def ana(data):
    for i, value in enumerate(data):
        if i > 0 and data[i] == 0:
            data[i] = data[i - 1]


def anaMax(data):
    max = 0
    for i, value in enumerate(data):
        if data[i] > max:
            max = data[i]
    return max


class ContrastDialog(QtWidgets.QDialog, Ui_UI_DataContrast):
    def __init__(self):
        super(ContrastDialog, self).__init__()
        self.setupUi(self)
        self.TdData_file_root_path = r'D:\LK\TMV煤矿项目\应力数据分析\obsdata'
        self.AkData_file_root_path = r'D:\LK\Project\data-plot\stressPrinter\Data'

        self.sID_TD_list = []
        self.sID_AK_list = []
        self.DF_ALL = pd.DataFrame(columns=['sID', 'time', 'ch1', 'ch2'])

        self.sync_tip_dialog = None

    def load_tddata_slot(self):
        Dir = QFileDialog.getExistingDirectory(self, '选择泰德数据目录', self.TdData_file_root_path)
        if not Dir:
            return
        self.TdData_file_root_path = Dir

        if not self.sync_tip_dialog:
            self.sync_tip_dialog = SyncTipDialog()
            self.sync_tip_dialog.show()  # 以非模态对话框模式弹出
        threading.Thread(target=self.load_tddata).start()

    def load_tddata(self):
        dirs = glob.glob(f'{self.TdData_file_root_path}/**/*.txt', recursive=True)

        for file in dirs:
            tddata = TDAna(file)
            sID = tddata.name
            if sID not in self.sID_TD_list:
                self.sID_TD_list.append(sID)
                newitem = QtWidgets.QListWidgetItem(f"{sID}-1")
                newitem.setCheckState(False)
                self.listWidget.addItem(newitem)
                newitem = QtWidgets.QListWidgetItem(f"{sID}-2")
                newitem.setCheckState(False)
                self.listWidget.addItem(newitem)
            self.DF_ALL = self.DF_ALL._append(tddata.df)
        self.DF_ALL.reset_index(drop=True, inplace=True)

        if self.sync_tip_dialog:
            self.sync_tip_dialog.close()
            self.sync_tip_dialog = None

    def load_akdata_slot(self):
        Dir = QFileDialog.getExistingDirectory(self, '选择安科数据目录', self.AkData_file_root_path)
        if not Dir:
            return
        self.AkData_file_root_path = Dir
        if not self.sync_tip_dialog:
            self.sync_tip_dialog = SyncTipDialog()
            self.sync_tip_dialog.show()  # 以非模态对话框模式弹出
        self.sID_TD_list = []
        threading.Thread(target=self.load_akdata).start()

    def load_akdata(self):
        dirs = glob.glob(f'{self.AkData_file_root_path}/**/*.xlsx', recursive=True)
        for file in dirs:
            aData = AnkeAna(file)
            for sID, dfi in aData.df.groupby('sID'):
                if sID not in self.sID_AK_list:
                    self.sID_AK_list.append(sID)
                    newitem = QtWidgets.QListWidgetItem(f"{sID}-1")
                    newitem.setCheckState(False)
                    self.listWidget.addItem(newitem)
                    newitem = QtWidgets.QListWidgetItem(f"{sID}-2")
                    newitem.setCheckState(False)
                    self.listWidget.addItem(newitem)
                self.DF_ALL = self.DF_ALL._append(dfi)
        self.DF_ALL.reset_index(drop=True, inplace=True)

        if self.sync_tip_dialog:
            self.sync_tip_dialog.close()
            self.sync_tip_dialog = None

    def draw_slot(self):
        start_time_str = self.dateEdit.dateTime().date().toString("yyyy-MM-dd 00:00:00")
        end_time_str = self.dateEdit_2.dateTime().date().toString("yyyy-MM-dd 23:59:59")

        if start_time_str >= end_time_str:
            print('开始时间不能大于结束时间！')
            return

        sIDs = []
        for i in range(self.listWidget.count()):
            if self.listWidget.item(i).checkState():
                sIDs.append(self.listWidget.item(i).text())

        data_list = []
        curDataList = []
        self.textBrowser.setText('')
        for item in sIDs:
            sID, chnNum = item.split('-')
            df_sel = self.DF_ALL[(start_time_str <= self.DF_ALL['time']) & (self.DF_ALL['time'] <= end_time_str) & (
                    self.DF_ALL['sID'] == sID)]
            df_sel['time'] = df_sel['time'].astype('datetime64[ns]')
            x = df_sel['time'].to_list()
            y = df_sel[f'ch{chnNum}'].to_list()
            ana(y)
            data_list.append((x, y))
            curDataList.append(f"{item}:{y[-1]}")
        if not data_list:
            print('没有找到数据！')
            return
        self.textBrowser.setText('\n'.join(curDataList))
        self.setViewTail(data_list=data_list, labels=sIDs)

    def setViewTail(self, data_list=None, labels=None):
        # 图例
        labels = LabelsInit.labelsInit(labels)
        self.pb_draw.setEnabled(False)

        self.fig_canvas = Figure_Canvas()  # 实例化类
        self.fig_canvas.drawFig(data_list=data_list, labels=labels, title=self.lineEdit.text())  # 调用类方法，作图
        self.graphicscene = QtWidgets.QGraphicsScene()  # 创建一个QGraphicsScene，因为加载的图形（FigureCanvas）不能直接放到graphicview控件中，必须先放到graphicScene，然后再把graphicscene放到graphicview中
        self.graphicscene.addWidget(self.fig_canvas)  # 把图形放到QGraphicsScene中，注意：图形是作为一个QWidget放到QGraphicsScene中的
        self.graphicsView.setScene(self.graphicscene)  # 把QGraphicsScene放入QGraphicsView
        self.graphicsView.show()  # 调用show方法呈现图形

        self.pb_draw.setEnabled(True)

    def draw_max_slot(self):
        self.pb_draw.setEnabled(False)
        start_time_str = self.dateEdit.dateTime().date().toString("yyyy-MM-dd 00:00:00")
        end_time_str = self.dateEdit_2.dateTime().date().toString("yyyy-MM-dd 23:59:59")

        sIDs = []
        for i in range(self.listWidget.count()):
            if self.listWidget.item(i).checkState():
                sIDs.append(self.listWidget.item(i).text())

        data_list = []
        if 'date' not in self.DF_ALL.columns:
            self.DF_ALL['date'] = self.DF_ALL['time'].astype('str').apply(lambda x: x[:10])
        for item in sIDs:
            sID, chnNum = item.split('-')
            df_sel = self.DF_ALL[(start_time_str <= self.DF_ALL['time']) & (self.DF_ALL['time'] <= end_time_str) & (
                    self.DF_ALL['sID'] == sID)]
            x = []
            y = []
            for idate, dfi in df_sel.groupby('date'):
                x.append(idate)
                y.append(dfi[f'ch{chnNum}'].max())
            data_list.append((x, y))
        self.setViewTail(data_list=data_list, labels=sIDs)

    def draw_finish_slot(self):
        self.pb_draw.setEnabled(True)

    def drawFig(self, data_list=None, data_list2=None, labels=None, title=''):
        if data_list is None:
            data_list = []
        if data_list2 is None:
            data_list2 = []
        if labels is None:
            labels = []
        # 创建一个Figure
        width = 12
        height = 6
        dpi = 100
        self.fig = plt.figure(figsize=(width, height), dpi=dpi, tight_layout=True)  # tight_layout: 用于去除画图时两边的空白
        plt.rcParams['figure.figsize'] = (width, height)
        plt.rcParams["font.sans-serif"] = ["Microsoft YaHei"]  # 设置默认字体
        plt.rcParams["axes.unicode_minus"] = False  # 坐标轴正确显示正负号
        self.ax = self.fig.add_subplot(111)

        data_legend = []
        for idata in data_list:
            line = self.ax.plot(idata[0], idata[1])
            data_legend.append(line[0])

        if data_list2:
            ax2 = self.ax.twinx()
            for idata in data_list2:
                line = ax2.plot(idata[0], idata[1], c='purple', alpha=0.2)
                data_legend.append(line[0])
            ax2.set_ylabel("摄氏度/℃")
        self.ax.legend(data_legend, labels, loc=2, bbox_to_anchor=(1.1, 1), shadow=True, fancybox=True)

        self.ax.set_title(title)
        self.ax.set_xlabel("时间")
        self.ax.set_ylabel("Mpa")

        locator = AutoDateLocator()
        date_fmt = DateFormatter("%Y-%m-%d %H:%M:%S")
        self.ax.xaxis.set_major_locator(locator)
        self.ax.xaxis.set_major_formatter(date_fmt)
        self.ax.tick_params(direction='in', length=6, width=2, labelsize=8)
        self.ax.xaxis.set_tick_params(labelrotation=45)
        plt.show()


class SyncTipDialog(QtWidgets.QDialog, Ui_DataSyncTip):
    def __init__(self):
        super(SyncTipDialog, self).__init__()
        self.setupUi(self)
        self.setWindowFlags(Qt.FramelessWindowHint)


'''
绘制图片线程
'''


class DrawQThread(QThread):
    statusRet = pyqtSignal(bool)

    def __init__(self, data_list=None, labels=None, parent=None):
        super(DrawQThread, self).__init__(parent)
        self.args = {
            "data_list": data_list,
            "labels": labels,
        }

    def run(self):
        AnkeDataPlot.draw(**self.args)
        self.statusRet.emit(True)


class Figure_Canvas(FigureCanvas):
    def __init__(self, parent=None, width=12, height=6, dpi=100):
        self.fig = plt.Figure(figsize=(width, height), dpi=dpi, tight_layout=True)
        FigureCanvas.__init__(self, self.fig)  # 初始化父类
        self.setParent(parent)
        self.axes = self.fig.add_subplot(111)

    def drawFig(self, data_list=None, data_list2=None, labels=None, title='对比分析'):
        if data_list is None:
            data_list = []
        if data_list2 is None:
            data_list2 = []
        if labels is None:
            labels = []

        data_legend = []
        for idata in data_list:
            line = self.axes.plot(idata[0], idata[1])
            data_legend.append(line[0])

        if data_list2:
            self.ax2 = self.axes.twinx()
            for idata in data_list2:
                line = self.ax2.plot(idata[0], idata[1], c='purple', alpha=0.2)
                data_legend.append(line[0])
            self.ax2.set_ylabel("摄氏度/℃")
        # plt.legend(data_legend, labels, loc=2, bbox_to_anchor=(1.1, 1), shadow=True, fancybox=True)

        self.axes.set_title(title)
        self.axes.set_xlabel("时间")
        self.axes.set_ylabel("Mpa")

        locator = AutoDateLocator()
        date_fmt = DateFormatter("%Y-%m-%d %H:%M:%S")
        self.axes.xaxis.set_major_locator(locator)
        self.axes.xaxis.set_major_formatter(date_fmt)
        self.axes.tick_params(direction='in', length=6, width=2, labelsize=8)
        self.axes.xaxis.set_tick_params(labelrotation=45)
        self.axes.legend(data_legend, labels, loc=2, bbox_to_anchor=(1.1, 1), shadow=True, fancybox=True)


def drawFig(data_list=None, data_list2=None, labels=None, title=''):
    if data_list is None:
        data_list = []
    if data_list2 is None:
        data_list2 = []
    if labels is None:
        labels = []
    # 创建一个Figure
    width = 12
    height = 6
    dpi = 100
    fig = plt.figure(figsize=(width, height), dpi=dpi, tight_layout=True)  # tight_layout: 用于去除画图时两边的空白
    plt.rcParams['figure.figsize'] = (width, height)
    plt.rcParams["font.sans-serif"] = ["Microsoft YaHei"]  # 设置默认字体
    plt.rcParams["axes.unicode_minus"] = False  # 坐标轴正确显示正负号
    ax = fig.add_subplot(111)

    data_legend = []
    for idata in data_list:
        line = ax.plot(idata[0], idata[1])
        data_legend.append(line[0])

    if data_list2:
        ax2 = ax.twinx()
        for idata in data_list2:
            line = ax2.plot(idata[0], idata[1], c='purple', alpha=0.2)
            data_legend.append(line[0])
        ax2.set_ylabel("摄氏度/℃")
    ax.legend(data_legend, labels, loc=2, bbox_to_anchor=(1.1, 1), shadow=True, fancybox=True)

    ax.set_title(title)
    ax.set_xlabel("时间")
    ax.set_ylabel("Mpa")

    locator = AutoDateLocator()
    date_fmt = DateFormatter("%Y-%m-%d %H:%M:%S")
    ax.xaxis.set_major_locator(locator)
    ax.xaxis.set_major_formatter(date_fmt)
    ax.tick_params(direction='in', length=6, width=2, labelsize=8)
    ax.xaxis.set_tick_params(labelrotation=45)
    plt.show()


if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    dialog = ContrastDialog()
    sys.exit(dialog.exec())
